package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"grpc_starter/grpc_interceptor/pb/pb"
	"time"
)

const (
	target  = "127.0.0.1:5001"
	OpenTLS = false
)

type customCredential struct {
}

func (c *customCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"x_token": "123",
		"app_id":  "456",
	}, nil
}

func (c *customCredential) RequireTransportSecurity() bool {
	return OpenTLS
}

func myClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	startAt := time.Now()

	err := invoker(ctx, method, req, reply, cc, opts...)

	grpclog.Infof("method=%s req=%v rep=%v duration=%s error=%v\n", method, req, reply, time.Since(startAt), err)

	return err
}

func main() {
	// custom interceptor on the client
	var opts = []grpc.DialOption{
		grpc.WithInsecure(),
		//grpc_demo.WithUnaryInterceptor(myClientInterceptor),
		grpc.WithPerRPCCredentials(new(customCredential)),
	}

	conn, err := grpc.Dial(target, opts...)
	if err != nil {
		fmt.Println("connect server is error")
		return
	}

	client := pb.NewGreetClient(conn)

	resData, err := client.Say(context.Background(), &pb.ReqData{Message: "golang"})
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(resData.Data)
}
